const { lowdb } = require('../../db/lowdb')
const { render } = require('../../utils/initRender')
const { SuccessModel, ErrorModel } = require('../../utils/index')
const { sequelize } = require('../../db/mysqldb/define')
const config = require('../../config')
const models = require('../../db/mysqldb/index')
const dfAdminAuthorityList = require('../../libs/dfAdminAuthorityList')
const dfUserAuthorityList = require('../../libs/dfUserAuthorityList')
const dfAdminRoleList = require('../../libs/dfAdminRoleList')
const dfUserRoleList = require('../../libs/dfUserRoleList')
const dfArticleTagList = require('../../libs/dfArticleTagList')
const dfArticleColumnList = require('../../libs/dfArticleColumnList')
const dfDynamicTopicList = require('../../libs/dfDynamicTopicList')
const {
  checkUserName,
  checkPwd,
  checkEmail
} = require('../../utils/validators')
const { encrypt } = require('../../utils/index')
class Init {
  static async renderGetIndex (req, res) {
    let init_is_success = lowdb.get('init.is_success').value()
    if (init_is_success) {
      await render(res, {
        title: 'init project',
        view_url: 'init/index',
        state: 'success',
        message: 'home'
      })
    } else {
      res.redirect('/init')
    }
  }
  static async cliSetStep (req, res) {
    let formData = req.body
    await lowdb
      .set('init.step', formData.step) // 通过set方法来对对象操作
      .write()
    await res.json(new SuccessModel(`step update success`))
  }
  static async cliInit (req, res) {
    await render(res, {
      title: 'init project',
      view_url: 'init/init',
      state: 'success',
      message: 'home'
    })
  }
  static async cliInitStepOne (req, res) {
    await render(res, {
      title: 'init project',
      view_url: 'init/init_step_one',
      state: 'success',
      message: 'home'
    })
  }
  static async cliInitStepTwo (req, res) {
    await render(res, {
      title: 'init project',
      view_url: 'init/init_step_two',
      state: 'success',
      message: 'home'
    })
  }
  static async cliInitStepThree (req, res) {
    await render(res, {
      title: 'init project',
      view_url: 'init/init_step_two',
      state: 'success',
      message: 'home'
    })
  }
  static async cliSetMysql (req, res) {
    const formData = req.body
    try {
      await lowdb.set('mysql', { ...formData }).write()
      await sequelize.sync({})
      await res.json(new SuccessModel(`mysql table create success`))
    } catch (error) {
      await res.json(new ErrorModel(`错误信息：${error.message}`))
      return false
    }
  }
  static async cliCreateAdminUser (req, res) {
    const reqData = req.body
    try {
      if (!reqData.account) {
        throw new ErrorMessage('请输入账户!')
      }
      if (!reqData.nickname) {
        throw new ErrorMessage('请输入昵称!')
      }
      if (!checkUserName(reqData.account)) {
        throw new ErrorMessage('账户须5-22个英文字符!')
      }
      if (!reqData.password) {
        throw new ErrorMessage('请输入密码!')
      }
      if (!checkPwd(reqData.password)) {
        throw new ErrorMessage(
          '密码格式输入有误，格式为字母与数字的组合，长度最小为6个字符!'
        )
      }

      if (!reqData.email_type) {
        throw new ErrorMessage('请选择邮箱类型')
      }

      if (!reqData.email) {
        throw new ErrorMessage('请填写邮箱地址!')
      }

      if (!checkEmail(reqData.email)) {
        throw new ErrorMessage('邮箱格式输入有误')
      }

      if (!reqData.email_password) {
        throw new ErrorMessage('请填写邮箱密码!')
      }

      if (reqData.email_type === 'company') {
        if (!reqData.email_host) {
          throw new ErrorMessage('请填写邮箱服务器地址!')
        }
        if (!reqData.email_port) {
          throw new ErrorMessage('请填写邮箱端口')
        }
      }

      if (!reqData.admin_url) {
        throw new ErrorMessage('请填写后台管理访问地址!')
      }
      await lowdb
        .set('email', {
          service: reqData.email_suffix || '',
          type: reqData.email_type || '',
          host: reqData.email_host || '',
          port: reqData.email_port || '',
          user: reqData.email || '',
          pass: reqData.email_password || ''
        })
        .set('website', {
          website_name: reqData.website_name || '',
          domain_name: reqData.domain_name || '',
          keywords: reqData.keywords || '',
          introduction: reqData.introduction || '',
          description: reqData.description || ''
        })
        .set('config', {
          admin_url: reqData.admin_url || 'admin',
          on_register: reqData.on_register,
          on_login: reqData.on_login,
          on_comment: reqData.on_comment,
          version: config.version
        })
        .write()

      await models.admin_authority.bulkCreate(dfAdminAuthorityList) // 导入默认后台管理员角色权限列表
      await models.user_authority.bulkCreate(dfUserAuthorityList) // 导入默认用户角色权限列表
      await models.admin_role.bulkCreate(dfAdminRoleList)
      await models.user_role.bulkCreate(dfUserRoleList)
      await models.article_tag.bulkCreate(dfArticleTagList)
      await models.article_column.bulkCreate(dfArticleColumnList)
      await models.dynamic_topic.bulkCreate(dfDynamicTopicList)
      const password = await encrypt(reqData.password, config.saltTime)
      console.log(password);

      await models.admin_user.create({
        // 创建默认超管角色
        account: reqData.account,
        avatar: config.default_avatar,
        nickname: reqData.nickname,
        password,
        admin_role_ids: config.SUPER_ROLE_ID,
        // reg_ip: ctx.request.ip,
        enable: true
      })

      await lowdb
        .get('init')
        .assign({
          is_success: true
        })
        .write()

      await res.json(new SuccessModel(`注册成功`))
    } catch (error) {
      await res.json(new ErrorModel(`错误信息：${error.message}`))
      return false
    }
  }
  static async cliRestartProject (ctx) {
    // 项目初始化成功后重启
    const Shell = require('./shell')
    Shell.Shell.esc()
  }
}

module.exports = {
  Init
}
